package com.mingyizhudao.app.view.booking;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dixiang.framework.common.QJNetUICallback;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.config.SystemConfig;
import com.dixiang.framework.http.DataHandler;
import com.dixiang.framework.utils.AlertDialogs;
import com.dixiang.framework.utils.BitmapCache;
import com.dixiang.framework.utils.Utils;
import com.dixiang.framework.widget.LoadingDialog;
import com.google.gson.reflect.TypeToken;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.common.IDataLoadListenter;
import com.mingyizhudao.app.http.DataUtils;
import com.mingyizhudao.app.moudle.bitmap.BimpTempHelper;
import com.mingyizhudao.app.moudle.bitmap.ImageGridActivity;
import com.mingyizhudao.app.moudle.bitmap.ImageItem;
import com.mingyizhudao.app.moudle.bitmap.NoScrollGridView;
import com.mingyizhudao.app.moudle.bitmap.PhotoActivity;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.IntentHelper;
import com.mingyizhudao.app.utils.ToastUtil;
import com.mingyizhudao.app.utils.UploadUtils;
import com.mingyizhudao.app.utils.UploadUtils.OnLoadListener;
import com.mingyizhudao.app.view.MYBaseActivity;
import com.mingyizhudao.app.view.PayViewActivity;
import com.mingyizhudao.app.view.mine.OrderListActivity;

public class FastBookingActivity extends MYBaseActivity{
	private NoScrollGridView noScrollgridview;
	private GridAdapter adapter;
	private BitmapCache cache;
	private List<ImageItem> dataChoosed = new ArrayList<ImageItem>();// 选中的item
	private Handler handler = new Handler();
	
	private String bookingId;
	private static final int FAIL = 500;// 更新下载进度的标记
	private static final int SUCCESS = 200;
	private ProgressDialog progressDialog;
	private String payUrl;
	
	private EditText et_hp,et_dpt,et_dt_name,et_p_name,et_phone,et_syscode,et_disease,et_dsc;
	private View get_code;
	private TextView btn_getsmscode;
	private Button btn_commit;
	private boolean hasLogin = false;
	private TimeCount timeCount;
	private Handler codeHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == Constants.Result_Status.RESULT_SCCESS){
				Toast.makeText(activity, "验证码已发送，注意查收！", 0)
				.show();
			}else if(msg.what == Constants.Result_Status.RESULT_FAILURE){
				timeCount.cancel();
				Toast.makeText(activity, "验证码发送失败！", 0).show();
				btn_getsmscode.setText("获取验证码");
				btn_getsmscode.setClickable(true);
				btn_getsmscode.setBackgroundResource(R.drawable.button_border_bg);
			}
		}
	};

	@Override
	public void initHeaderView() {
		setTopViewBg(R.color.actionbar_bg_color);
		initBackView(R.drawable.left_back_white_icon, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		setTitleViewValue(0, 0, R.color.white);
		setTitleViewValue("快速预约");
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fast_booking);
		initView();
	}
	
	private void initView(){
		
		
		progressDialog = new ProgressDialog(this);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setMessage("上传中...");
		
		
		noScrollgridview = (NoScrollGridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		cache = new BitmapCache(this, Constants.PHOTOWIDTH);
		
		adapter = new GridAdapter(this);
		noScrollgridview.setAdapter(adapter);
		noScrollgridview
		.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 == dataChoosed.size()) {

					// IntentHelper.getInstance(activity).gotoActivity(ImageGridActivity.class,
					// null, 1011);
					Intent intent = new Intent(activity,
							ImageGridActivity.class);
					startActivityForResult(intent, 1011);
					// intent.putExtra("isDymic", true);
					// startActivity(intent);
				} else {
					Intent intent = new Intent(activity,
							PhotoActivity.class);
					intent.putExtra("ID", arg2);
					startActivityForResult(intent, 1012);
				}
			}
		});
		
		
		et_hp = (EditText) findViewById(R.id.et_hp);
		et_dpt = (EditText) findViewById(R.id.et_dpt);
		et_dt_name = (EditText) findViewById(R.id.et_dt_name);
		et_p_name = (EditText) findViewById(R.id.et_p_name);
		et_phone = (EditText) findViewById(R.id.et_phone);
		et_syscode = (EditText) findViewById(R.id.et_syscode);
		et_disease = (EditText) findViewById(R.id.et_disease);
		et_dsc = (EditText) findViewById(R.id.et_dsc);
		
		get_code = findViewById(R.id.get_code);
		
		btn_commit = (Button) findViewById(R.id.btn_commit);
		
		btn_getsmscode = (TextView) findViewById(R.id.btn_getsmscode);
		
		btn_getsmscode.setOnClickListener(onClickListener);
		
		String token = CommonUtils.getToken(this);
		if(token!=null&&token.length()>0&&!"null".equals(token)){
			hasLogin = true;
			get_code.setVisibility(View.GONE);
		}
		timeCount = new TimeCount(60000, 1000);// 构造CountDownTimer对象
	}

	public void onBooking(View view){
		checkData();
	}
	
	public void onSendSysCode(){
		String phone = et_phone.getText().toString().trim();
		if(Utils.checkMobile(phone)){
			timeCount.start();// 开始计时
			Map params = new HashMap<String , Object>();
			params.put("smsVerifyCode[mobile]", phone);
			params.put("smsVerifyCode[action_type]", 200);
			DataUtils.getInitial().getSmscode(activity, params,codeHandler);
			return;
		}
		et_phone.requestFocus();
		ToastUtil.showToast(this, "请核对您的手机号码！");
	}
	
	private void checkData(){
		String hp_name = et_hp.getText().toString().trim();
		String dpt_name = et_dpt.getText().toString().trim();
		String dct_name = et_dt_name.getText().toString().trim();
		String p_name = et_p_name.getText().toString().trim();
		String phone = et_phone.getText().toString().trim();
		String sysCode = et_syscode.getText().toString().trim();
		String disease = et_disease.getText().toString().trim();
		String dsc = et_dsc.getText().toString().trim();
		
		final Map map = new HashMap<String,Object>();
		map.put("booking[hospital_name]", hp_name);
		map.put("booking[hp_dept_name]", dpt_name);
		map.put("booking[doctor_name]", dct_name);
		
		if(Utils.isStringEmpty(p_name)){
			et_p_name.requestFocus();
			ToastUtil.showToast(this, "填写患者姓名");
			return;
		}
		
		if(hasLogin){
			map.put("booking[username]", CommonUtils.getMobile(activity));
			map.put("booking[token]", CommonUtils.getToken(activity));
		}else{
			if(!Utils.checkMobile(phone)){
				et_phone.requestFocus();
				ToastUtil.showToast(this, "请核对您的手机号码！");
				return;
			}
			if(Utils.isStringEmpty(sysCode)){
				et_syscode.requestFocus();
				ToastUtil.showToast(this, "请输入验证码");
				return;
			}
			map.put("booking[mobile]", phone);
			map.put("booking[verify_code]", sysCode);
		}

		map.put("booking[contact_name]", p_name);
		map.put("booking[disease_name]", disease);
		map.put("booking[disease_detail]", dsc);
		
		
		
		if (dataChoosed != null && dataChoosed.size() > 0) {
			AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
			dlg.setOk( "提交" );
			dlg.showAlertDialog(
					"您已经选中了" + dataChoosed.size() + "张影像资料,确认提交！",
					new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							String path = DataUtils.getInitial().doFastBooking(activity, getIntent().getStringExtra(Constants.PARM_ACTION_URL), map, listenter);
						}
					});
		} else {
			AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
			dlg.setOk( "提交" );
			dlg.setContent2(true, "（可以在预约单详情界面添加）" );
			dlg.showAlertDialog(
					"您尚未上传影像资料,确认提交？",
					new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							String path = DataUtils.getInitial().doFastBooking(activity, getIntent().getStringExtra(Constants.PARM_ACTION_URL), map, listenter);
						}
					});
		}
		
		
	}
	
	private IDataLoadListenter listenter = new IDataLoadListenter() {
		
		@Override
		public void onSuccess(Object result) {
			if(result != null){
				Map<String, Object> map = (Map<String, Object>)result;
			   
				bookingId = map.get("booking_id")+"";
				
				String refNo = map.get("refNo")+"";
				String token = (String) map.get("token");
				
				if(token!=null&&token.length()>0&&!"null".equals(token)){
					CommonUtils.setToken(activity, token);
					String phone = et_phone.getText().toString().trim();
					CommonUtils.setMobile(activity, phone);
				}
				//上传到七牛的图片地址
				String fileUrl = map.get("actionUrl")+"";
				
				payUrl = CommonUtils.getPayUrl(activity, refNo);
				
				if (dataChoosed != null && dataChoosed.size() > 0) {
					upQiniu();
					
				} else {
					gotoResultView();
				}

			}else {
				ToastUtil.showToast(activity, "预约单提交失败！",Toast.LENGTH_SHORT);
			}
		}
		
		@Override
		public void onError(Exception e, Object result) {
			
		}
		
		@Override
		public void onCompleted(Exception e, Object result) {
		}
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if (requestCode==1) {
			IntentHelper.getInstance(activity).gotoActivity(OrderListActivity.class);
			finish();
		}else {
			dataChoosed = BimpTempHelper.getInstance().getImageItemsChoosend();
			// if(dataChoosed != null && dataChoosed.size() > 0){
			noScrollgridview.setAdapter(adapter);
			// }
		}
		
	};
	
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.btn_getsmscode:
				onSendSysCode();
				break;
			default:
				break;
			}
		}
	};
	
	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btn_getsmscode.setText("获取验证码");
			btn_getsmscode.setClickable(true);
			btn_getsmscode.setBackgroundResource(R.drawable.button_border_bg);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			btn_getsmscode.setClickable(false);
			btn_getsmscode.setBackgroundColor(getResources().getColor(
					R.color.btn_timing_gray));

			btn_getsmscode.setText(millisUntilFinished / 1000 + "秒后重发");
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			AlertDialogs.getAlertDialog(activity).showAlertDialog("你确定要放弃编辑吗？", new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					finish();
				}
			});
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
	
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			if (dataChoosed.size() == Constants.PHOTO_MAX_SIZE) {
				return Constants.PHOTO_MAX_SIZE;
			}
			return (dataChoosed.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.myablum_item, parent,
						false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.blum_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (position == dataChoosed.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == Constants.PHOTO_MAX_SIZE) {
					holder.image.setVisibility(View.GONE);
					convertView.setVisibility(View.GONE);
				}

			} else {
				cache.displayBmp(holder.image,
						dataChoosed.get(position).imagePath, handler);
			}
			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

	}
	
	
	 private void upQiniu() {
		 progressDialog.show();
			final List<File> files = new ArrayList<File>();
			for (int i = 0; i < dataChoosed.size(); i++) {
				files.add(new File(dataChoosed.get(i).imagePath));
			}
			
			UploadUtils uploadUtils =new UploadUtils( bookingId);
			
			uploadUtils.uploadFiles(activity, null, files, new OnLoadListener() {
				
				@Override
				public void onLoadSuccess(String remoteDomain ,String key, String str, int index) {
					doTestNet(remoteDomain ,files.get(index), index  ,key);
					
				}
				
				@Override
				public void onLoadSuccess(String remoteDomain ,String key, String str) {
					LoadingDialog.getInstance(activity).dismiss();
				}
				
				@Override
				public void onLoadFail() {
					progressDialog.dismiss();
					LoadingDialog.getInstance(activity).dismiss();
					Toast.makeText(activity, "上传失败！", Toast.LENGTH_LONG).show();
					
				}
			});
			
		}
	 private Handler mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {

				case SUCCESS:
					progressDialog.dismiss();
					Toast.makeText(activity, "上传成功！", 2000).show();
					gotoResultView();
					break;
				case FAIL:
					progressDialog.dismiss();
					Toast.makeText(activity, "上传失败！", 2000).show();
					break;
				default:
					break;
				}
			}
		};
	 
		private void gotoResultView() {
//			IntentHelper.getInstance(activity).gotoActivityWithURL(PayViewActivity.class, payUrl);
			Intent intent = new Intent(activity,PayViewActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString(Constants.PARM_ACTION_URL, payUrl);
			bundle.putString(Constants.PARM_PAGE_TITLE, "支付");
			intent.putExtras(bundle);
			startActivityForResult(intent, 1);
		}
		
		
	 //上传七牛成功数据保存至自己服务器
	  	@SuppressWarnings("unchecked")
	  	private void doTestNet(String remoteDomain ,File file ,final int index, String key) {

	  		Map map = new HashMap<String, Object>();
	  		
	  		map.put("appFile[token]", CommonUtils.getToken(activity));
	  		map.put("appFile[username]", CommonUtils.getMobile(activity));
	  		
	  		map.put("appFile[size]", file.length()/1024+"");
	  		if (file.getName().endsWith(".png")) {
	  			map.put("appFile[type]", "png");
	  		}else {
	  			map.put("appFile[type]", "jpg");
	  		}
	  		
	  		map.put("appFile[remoteDomain]", remoteDomain);
	  		map.put("appFile[remoteKey]", key);
	  		
	  		map.put("appFile[bookingId]", bookingId);
	  		
	  		
	  		
	  		QJNetUICallback callback = new QJNetUICallback<QjResult<HashMap<String, Object>>>(activity) {
				@Override
				public void onSuccess(QjResult<HashMap<String, Object>> result) {
					if (result != null) {
							if (index+1 ==dataChoosed.size()) {
								//ToastUtil.showToast(activity, "提交自己服务器成功！",Toast.LENGTH_LONG);
								mHandler.sendEmptyMessage(SUCCESS);
						} 
						}else {
							mHandler.sendEmptyMessage(FAIL);
					}
				}

				public void onError(Exception e, QjResult<HashMap<String, Object>> result) {
					super.onError(e, result);
					  ToastUtil.showToast(activity, "提交自己服务器失败！",Toast.LENGTH_LONG);
					mHandler.sendEmptyMessage(FAIL);
				}

				public void onCompleted(Exception e, QjResult<HashMap<String, Object>> result) {
					super.onCompleted(e, result);
				}
			};
			String path = new DataHandler().postDataObject(activity, SystemConfig.SAVE_APP_FILE ,map, new TypeToken<QjResult<HashMap<String, Object>>>() {}, callback);

	  	}
	  	
	  	@Override
		protected void onDestroy() {
			BimpTempHelper.getInstance().clearData();
			super.onDestroy();
		}
}
